package com.yunxin.facerecognition.network.operate;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;

import com.common.network.HttpGetResponse;
import com.common.network.RetrofitManager;
import com.common.network.RetrofitModule;
import com.common.network.conversion.JsonConverterFactory;
import com.common.network.request.BaseRequest;
import com.common.network.response.BaseResponse;
import com.google.gson.Gson;
import com.yunxin.facerecognition.app.MyApp;
import com.yunxin.facerecognition.component.DaggerNetworkOperateComponent;
import com.yunxin.facerecognition.component.NetworkOperateComponent;
import com.yunxin.facerecognition.network.HttpInterfaceManager;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Retrofit;


/**
 * Created by Administrator on 2017/3/29.
 */

public class FaceRecognitionFileUploadOperateRequest extends RetrofitManager {

    private String TAG = "GoNativeServiceFileUploadOperateRequest";

    private NetworkOperateComponent networkOperateComponent = null;

    @Inject
    Retrofit retrofit;

    @Inject
    Context context;


    private static class LazyHolder {
        private static final FaceRecognitionFileUploadOperateRequest INSTANCE = new FaceRecognitionFileUploadOperateRequest();
    }

    private FaceRecognitionFileUploadOperateRequest() {

    }

    public static FaceRecognitionFileUploadOperateRequest instance() {
        return LazyHolder.INSTANCE;
    }

    public void faceRecognitionFileUpload(final BaseRequest baseRequest, String username, String company, String mobile, String photo) {

        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("username", username)
                .addFormDataPart("company", company)
                .addFormDataPart("mobile", mobile)
                .addFormDataPart("file", photo,
                        RequestBody.create(MediaType.parse("multipart/form-data"), baseRequest.getFileUpload()))
                .build();

        fileUpload(baseRequest, requestBody);
    }


    public void faceRecognitionFileUpload(final BaseRequest baseRequest, String photo) {

        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", photo,
                        RequestBody.create(MediaType.parse("multipart/form-data"), baseRequest.getFileUpload()))
                .build();

        fileUpload(baseRequest, requestBody);
    }


    public void fileUpload(final BaseRequest baseRequest, RequestBody requestBody) {

        //缓存值

  /*      ProgressRequestBody.ProgressListener progressListener = new ProgressRequestBody.ProgressListener() {
            @Override
            public void onProgress(long bytesWritten, long contentLength, int progress) {
                FileUploadOriginal fileUploadOriginal = new FileUploadOriginal();
                fileUploadOriginal.setFileState(1);
                fileUploadOriginal.setFileProgress(progress);
                BaseResponse baseResponse = baseRequest.getResponse();
                baseResponse.setData(fileUploadOriginal);

                EventBus.getDefault().post(baseResponse);
            }
        };

        ProgressRequestBody content = new ProgressRequestBody(requestBody, progressListener);*/

        baseRequest.setContent(requestBody);

        if (networkOperateComponent == null) {
            networkOperateComponent = DaggerNetworkOperateComponent.builder().appComponent(((MyApp) MyApp.context).getAppComponent()).retrofitModule(new RetrofitModule(baseRequest.getHttpUrl(), 2, null, JsonConverterFactory.create())).build();
            networkOperateComponent.inject(this);
        }

        retrofit.create(HttpInterfaceManager.class).commonFileUploadRequest(baseRequest.getFileUrl(), baseRequest.getContent()).
                subscribeOn(Schedulers.trampoline()).observeOn(Schedulers.trampoline()).
                subscribe(new Consumer<Object>() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void accept(Object o) throws Exception {
                        try {
                            JSONObject jsonObject = new JSONObject((String) o);
                            int status = jsonObject.getInt("state");
                            if (0 == status) {
                                HttpGetResponse httpResponse = new HttpGetResponse();
                                httpResponse.setSource(jsonObject.getString("data"));
                                Log.d(TAG, "1-------------- =" + httpResponse.getSource());
                                Gson gson = new Gson();
                                Object obj;
                                if (httpResponse.getSource().charAt(0) == '{') {
                                    //对象
                                    obj = gson.fromJson(httpResponse.getSource(), baseRequest.getOriginalData().getClass());
                                } else if (httpResponse.getSource().charAt(0) == '[') {
                                    //集合
                                    JSONArray jsonArray = new JSONArray(httpResponse.getSource());
                                    List<Object> objects = new ArrayList<>();
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        objects.add(gson.fromJson(jsonArray.getString(i), baseRequest.getOriginalData().getClass()));
                                    }
                                    obj = objects;
                                } else {
                                    obj = o;
                                }

                                //转换层
                                if (baseRequest.getConversion() != null) {
                                    obj = baseRequest.getConversion().originalConversionResult(obj, baseRequest.getTag());
                                }

                                BaseResponse baseResponse = baseRequest.getResponse();
                                baseResponse.setData(obj);

                                EventBus.getDefault().post(baseResponse);
                            } else {
                                //失败
                                String data = jsonObject.getString("data");
                                JSONObject jsonObject1 = new JSONObject(data);
                                String error = URLDecoder.decode(jsonObject1.getString("msg"), "UTF-8");
                                BaseResponse baseResponse = baseRequest.getResponse();
                                baseResponse.setError(error);
                                EventBus.getDefault().post(baseResponse);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        errorInfo(FaceRecognitionFileUploadOperateRequest.this.context, throwable, baseRequest.getResponse());
                    }
                });
    }

}
